// 登录注册
const path = require('path');
const db = require(path.join(__dirname, '../common/db.js'));
const jwt = require('jsonwebtoken');
const utility = require('utility');
const express = require('express');
const router = express.Router();

// router.get('/data', async (req, res) => {
//     let params = 3;
//     let sql = 'select * from book where id = ?';
//     let ret = await db.db(sql, params);
//     res.send(ret);
// })

// 注册
router.post('/reguser', async (req, res) => {
    let params = req.body;
    let cSql = 'select id from user where username = ?';
    let isUser = await db.db(cSql, params.username);
    if (isUser.length > 0) { // 已注册
        res.json({
            status: 1,
            message: '您已注册'
        });
        return;
    }
    params.password = utility.md5(params.password);
    let sql = 'insert into user set ?';
    let ret = await db.db(sql, params);
    if (ret['affectedRows'] > 0) { // 插入成功
        res.json({
            status: 0,
            message: '注册成功'
        });
    } else {
        res.json({
            status: 1,
            message: '注册失败'
        });
    }
})

// 登录
router.post('/login', async (req, res) => {
    let params = req.body;
    params.password = utility.md5(params.password);
    let sql = 'select id from user where username = ? and password = ?';
    let ret = await db.db(sql, [params.username, params.password]);
    if (ret.length > 0) { // 登录成功
        let token = jwt.sign({id: ret[0].id}, 'JWT-Secret', {expiresIn: '2 days'});
        res.json({
            status: 1,
            message: '登录成功',
            token: 'Bearer ' + token
        });
    } else {
        res.json({
            status: 1,
            message: '登录失败'
        });
    }
})


module.exports = router;